"""
用户评分评论管理路由
提供用户评分评论的增删改查功能
"""

from typing import Optional
from fastapi import APIRouter, Header, Query, Body
from fastapi.responses import JSONResponse
from utils.password_utils import get_user_id_from_jwt
from db.operations import UserRatingsCommentsOperations
from model.message_model import Message
from model.user_ratings_model import (
    UserRating,
    UserRatingRequest,
    UserRatingListResponse,
)

# 创建用户评分评论相关的子路由
router = APIRouter(
    prefix="/ratings",
    tags=["ratings"],
    responses={404: {"description": "Not found"}},
)


@router.get("/", summary="用户评分评论管理接口信息")
async def get_ratings_info():
    """获取用户评分评论管理接口信息和使用示例"""
    api_info = {
        "message": "用户评分评论管理API接口",
        "endpoints": {
            "GET /api/ratings/": "获取用户评分评论管理接口信息",
            "POST /api/ratings/update": "添加/修改评论",
            "DELETE /api/ratings/delete": "删除评论",
            "GET /api/ratings/book": "获取一本书的评论列表（支持分页）",
        },
        "examples": {
            "添加/修改评论": {
                "url": "/api/ratings/update",
                "method": "POST",
                "header": "Bearer token",
                "body": {"book_id": 123, "rating": 8.5, "comment": "这本书很好看"},
                "description": "为图书ID为123的图书添加8.5分评价和评论",
            },
            "删除评论": {
                "url": "/api/ratings/delete?book_id=123",
                "method": "DELETE",
                "header": "Bearer token",
                "description": "删除对图书ID为123的评论",
            },
            "获取评论列表": {
                "url": "/api/ratings/book?book_id=123&page=1&limit=10",
                "method": "GET",
                "description": "获取图书ID为123的第1页评论，每页10条",
            },
        },
    }
    return JSONResponse(status_code=200, content=api_info)


@router.post("/update", summary="添加/修改评论")
async def update_rating(
    request: UserRatingRequest = Body(..., description="评分评论信息"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    """添加或修改用户评分评论"""
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None

    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        # 准备评分评论数据
        ratings_ops = UserRatingsCommentsOperations()

        # 创建评分评论数据
        rating_data = UserRating(
            user_id=user_id,
            book_id=request.book_id,
            rating=request.rating,
            comment=request.comment,
        ).model_dump()

        result = await ratings_ops.batch_upsert_ratings_comments([rating_data])

        if result == 0:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="评分评论保存失败",
                ).model_dump(),
            )

        return JSONResponse(
            status_code=200,
            content=Message(
                message="评分评论保存成功",
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=Message(
                message=f"保存评分评论失败: {str(e)}",
            ).model_dump(),
        )


@router.delete("/delete", summary="删除评论")
async def delete_rating(
    book_id: Optional[int] = Query(..., description="图书ID"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    """删除用户评分评论"""
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None

    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        ratings_ops = UserRatingsCommentsOperations()

        # 构建删除条件
        user_book_pairs = {
            "user_id": user_id,
            "book_id": book_id,
        }

        result = await ratings_ops.batch_delete_ratings_comments([user_book_pairs])

        if result == 0:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="未找到要删除的评论",
                ).model_dump(),
            )

        return JSONResponse(
            status_code=200,
            content=Message(
                message="评论删除成功",
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=Message(
                message=f"删除评论失败: {str(e)}",
            ).model_dump(),
        )


@router.get("/list", summary="获取一本书的评论列表")
async def get_book_ratings(
    book_id: Optional[int] = Query(..., description="图书ID"),
    page: Optional[int] = Query(1, ge=1, description="页码"),
    limit: Optional[int] = Query(10, ge=1, le=50, description="每页数量，最多50条"),
):
    """获取指定图书的评分评论列表，支持分页"""
    try:
        ratings_ops = UserRatingsCommentsOperations()

        # 获取评论列表和总数
        total, ratings_list = (
            await ratings_ops.get_book_ratings_comments_with_pagination(
                book_id=book_id,
                page=page,
                limit=limit,
            )
        )
        # 转换为响应模型
        ratings_with_user = [UserRating(**rating) for rating in ratings_list]

        return JSONResponse(
            status_code=200,
            content=UserRatingListResponse(
                message="获取评论列表成功",
                ratings_list=ratings_with_user,
                page=page,
                limit=limit,
                total=total,
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=UserRatingListResponse(
                message=f"获取评论列表失败: {str(e)}",
                ratings_list=[],
                page=page,
                limit=limit,
                total=0,
            ).model_dump(),
        )
